package com.uflower.user.interceptor;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.uflower.common.to.UserLoginTo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserLoginTo> loginUser = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //对于特定路径的访问直接放行，解决远程调用丢失cookie问题
        String uri = request.getRequestURI();
        boolean match = new AntPathMatcher().match("/login/**",uri);
        if(match){
            return true;
        }
        //获取token并解析
        String token = null;
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length>0){
            //从cookie中取token
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("token")){
                    token =cookie.getValue();
                }
            }
        }else{
            //从header中取token
            token = request.getHeader("token");
        }
        if(token != null&&JWTUtil.verify(token,"uflower".getBytes())){
            JWT jwt = JWTUtil.parseToken(token);
            UserLoginTo userLoginTo = new UserLoginTo();
            Object ido = jwt.getPayload("id");
            if(ido instanceof Integer){
                userLoginTo.setId(Long.valueOf(((Integer)ido).toString()));
            }else{
                userLoginTo.setId((Long)ido);
            }
            userLoginTo.setUsername((String) jwt.getPayload("username"));
            loginUser.set(userLoginTo);
            return true;
        }else {
            response.sendRedirect("http://localhost:88/api/user/errorlogin");
            return false;
        }

//        UserLoginTo userLoginTo = new UserLoginTo();
//        userLoginTo.setId(4L);
//        userLoginTo.setUsername("张三");
//        loginUser.set(userLoginTo);
//        return true;
    }
}